import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/auto_router.dart';
import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/coustom_outline_button.dart';
import 'package:casdon/common/widget/conform_dialog.dart';
import 'package:casdon/common/widget/gradient_button.dart';
import 'package:casdon/core/utils/toast_utils.dart';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';

@RoutePage()
class PairnetSuccessScreen extends ConsumerStatefulWidget {
  final String devId;
  const PairnetSuccessScreen({super.key, required this.devId});

  @override
  ConsumerState<PairnetSuccessScreen> createState() =>
      _PairnetSuccessScreenState();
}

class _PairnetSuccessScreenState extends ConsumerState<PairnetSuccessScreen> {
  ThingSmartDeviceModel? _device;
  String? _newName;
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _fetchDevice();
  }

  Future<void> _fetchDevice() async {
    setState(() => _loading = true);
    final dev = await TuyaService().getDeviceById(devId: widget.devId);
    if (!mounted) return;
    setState(() {
      _device = dev;
      _loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: CommonAppBar(title: '添加设备', onBack: () => _goHomePage(context)),
      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : Column(
              children: [
                _buildSuccessHeader(context),
                _buildDeviceInfoCard(
                  context,
                  _newName ?? _device?.name ?? '设备',
                  _device?.iconUrl ?? '',
                ),
                const Spacer(),
                _buildActionButtons(context, _device),
                SizedBox(height: 155.h),
              ],
            ),
    );
  }

  Widget _buildSuccessHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 40.h),
      child: Column(
        children: [
          Container(
            width: 48.w,
            height: 48.w,
            decoration: BoxDecoration(
              color: const Color(0xFF2BA471),
              shape: BoxShape.circle,
            ),
            child: Icon(Icons.check, color: Colors.white, size: 30.w),
          ),
          SizedBox(height: 16.h),
          Text(
            '添加成功',
            style: context.textTheme.headlineLarge?.copyWith(
              color: context.customColorThemeNonNull.textColor1,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDeviceInfoCard(
    BuildContext context,
    String deviceName,
    String devIconUrl,
  ) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 12.w),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: context.customColorThemeNonNull.gray1,
        borderRadius: BorderRadius.circular(6.r),
      ),
      child: Row(
        children: [
          Container(
            width: 48.w,
            height: 48.w,
            decoration: BoxDecoration(
              color: Colors.grey[300],
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Image.network(
              devIconUrl,
              width: 40.w,
              height: 40.h,
              fit: BoxFit.contain,
            ),
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  deviceName,
                  style: context.textTheme.bodyMedium?.copyWith(
                    color: context.customColorThemeNonNull.textColor1,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ],
            ),
          ),
          GestureDetector(
            onTap: () => _showRenameDialog(context),
            child: Text(
              '修改名称',
              style: context.textTheme.bodyMedium?.copyWith(
                color: context.colorScheme.primary,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildActionButtons(
    BuildContext context,
    ThingSmartDeviceModel? devModel,
  ) {
    return Padding(
      padding: EdgeInsets.all(16.w),
      child: Row(
        children: [
          Expanded(
            child: CustomOutlineButton(
              onPressed: () => _openDevicePanel(context, devModel),
              text: '打开面板',
              borderColor: context.colorScheme.primary,
              borderRadius: 24,
            ),
          ),
          SizedBox(width: 16.w),
          Expanded(
            child: GradientButton(
              text: '完成',
              borderRadius: 24,
              onPressed: () => _completed(context),
            ),
          ),
        ],
      ),
    );
  }

  void _showRenameDialog(BuildContext context) async {
    if (!context.mounted) return;
    final result = await showInputDialog(
      context: context,
      title: '修改名称',
      hintText: '输入新名称',
    );
    if (result != null && result.isNotEmpty) {
      final success = await TuyaService().renameDevice(
        deviceId: _device!.devId!,
        name: result.trim(),
      );
      if (success) {
        setState(() {
          _newName = result.trim();
        });
      } else {
        ToastUtil.show('设备名称修改失败');
      }
    }
  }

  void _openDevicePanel(
    BuildContext context,
    ThingSmartDeviceModel? devModel,
  ) async {
    if (devModel == null) return;
    // 打开设备面板的逻辑

    context.router.popUntilRouteWithName(TabRoute.name);
    await Future.delayed(const Duration(milliseconds: 1000));
    // 打开设备面板
    // await TuyaService().gotoPanel( devId);
    await TuyaService().gotoPanel(
      deviceId: widget.devId,
      pid: devModel.productId,
      fromType: PanelFromType.home,
    );
  }

  void _completed(BuildContext context) {
    // 返回首页
    context.router.popUntilRouteWithName(TabRoute.name);
  }

  void _goHomePage(BuildContext context) {
    context.router.popUntilRouteWithName(TabRoute.name);
  }
}
